import 'package:dio/dio.dart';
import 'package:fish_redux/fish_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'action.dart';
import 'state.dart';

Effect<DeviceLogDetailState> buildEffect() {
  return combineEffects(<Object, Effect<DeviceLogDetailState>>{
    DeviceLogDetailAction.action: _onAction,
    Lifecycle.initState: _refresh,
    DeviceLogDetailAction.reload: _refresh,
    DeviceLogDetailAction.clearFilterMsg: _clearFilterMsg,
    DeviceLogDetailAction.filter: _filterMsg,
  });
}

void _onAction(Action action, Context<DeviceLogDetailState> ctx) {}

void _refresh(Action action, Context<DeviceLogDetailState> ctx) async {
  var response = await Dio().get(ctx.state.url);
  ctx.state.msgList.clear();
  if (response.statusCode == 200) {
    String allMsg = response.data;
    allMsg.split('\r\n').forEach((line) {
      ctx.state.msgList.add(line);
    });
    _filterMsg(action, ctx);
  } else {
    Fluttertoast.showToast(msg: '请求失败，请重试');
  }
}

void _filterMsg(Action action, Context<DeviceLogDetailState> ctx) async {
  var filterNode = ctx.state.mController.text;
  ctx.state.msgFliterList.clear();
  ctx.state.msgList.forEach((line) {
    if (filterNode.isEmpty || line.contains(filterNode)) {
      ctx.state.msgFliterList.add(line);
    }
  });
  ctx.dispatch(DeviceLogDetailActionCreator.refreshUI());
}

void _clearFilterMsg(Action action, Context<DeviceLogDetailState> ctx) async {
  ctx.state.mController.clear();
  _filterMsg(action, ctx);
}
